package net.devkit.core.module.sys.service.impl;

import javax.annotation.Resource;

import net.devkit.common.dao.GenericDao;
import net.devkit.common.service.impl.BaseServicerImpl;
import net.devkit.common.toolkit.DevTool;
import net.devkit.common.toolkit.FilterCollection;
import net.devkit.common.toolkit.Pager;
import net.devkit.common.toolkit.SHAEncryptUtils;
import net.devkit.common.toolkit.reflection.ReflectionUtils;
import net.devkit.common.toolkit.retval.RetcodeWrapper;
import net.devkit.core.module.sys.dao.UserDao;
import net.devkit.core.module.sys.service.UserServicer;
import net.devkit.core.pojo.db.User;
import net.devkit.core.pojo.helper.PagerHelper;

import org.springframework.stereotype.Service;

@Service("userServicer")
public class UserServicerImpl extends BaseServicerImpl<User, String> implements
		UserServicer {

	private UserDao userDao;

	@Resource(name = "userDao")
	@Override
	public void setGenericDao(GenericDao<User, String> genericDao) {
		this.genericDao = genericDao;
		this.userDao = (UserDao) genericDao;
	}

	@Override
	public RetcodeWrapper<User> login(String loginname, String passwd) {
		RetcodeWrapper<User> retval = null;

		final StringBuilder jpql = new StringBuilder(
				"from User user where user.userName = ? and user.isDel = ? ");
		User user = userDao.findUniqueEntityByJpql(jpql, loginname, false);

		// user为空，表示用户名不存在
		if (DevTool.isEmpty(user)) {
			retval = new RetcodeWrapper<User>(
					UserServicer.LOGIN_FAILED_LOGINNAME_NOTEXISTS);
			return retval;
		}

		if (!user.getPasswd().equals(SHAEncryptUtils.getDigestOfString(passwd))) {// 用户密码不匹配，表示密码错误
			retval = new RetcodeWrapper<User>(
					UserServicer.LOGIN_FAILED_PASSWD_ERROR, new User(
							user.getId()));
		} else if (user.getStatus().equals(User.STATUS_DISABLE)) {// 判断用户是否被禁用
			retval = new RetcodeWrapper<User>(
					UserServicer.LOGIN_FAILED_ACCOUNT_DISABLE, new User(
							user.getId()));
		} else {
			retval = new RetcodeWrapper<User>(UserServicer.LOGIN_SUCCESS, user);
		}
		return retval;
	}

	@Override
	public Pager<User> findUserPager(PagerHelper helper) {
		FilterCollection fc = new FilterCollection(" user.isDel = ? ", false)
				.addFilter(" user.status = ? ", User.STATUS_ENABLE).addOrder(
						helper.getSortname(),helper.getSortorder());

		return userDao.findPagerByJpql(helper.getPagesize(),
				helper.getPageno(),
				userDao.obtainJpqlOfBasic().append(fc.getWhereClause()), fc
						.getArgs().toArray());
	}

	@Override
	public void moidfyUserInfo(User user) {
		User dbUser = userDao.findEntityById(user.getId());
		ReflectionUtils.copyProperties(user, dbUser, "nickName","telNum","email","sex","status");
		userDao.modify(dbUser);
	}

}
